<template>
  <div>
    <!-- 搜索 -->
    <div class="search">
      <el-input placeholder="请输入订单号" clearable v-model="queryInfo.no"></el-input>
      <el-input placeholder="请输入用户名" clearable v-model="queryInfo.userName"></el-input>
      <el-select placeholder="选择订单状态" clearable v-model="queryInfo.status">
        <el-option label="待付款" value="待付款"></el-option>
        <el-option label="待发货" value="待发货"></el-option>
        <el-option label="待收货" value="待收货"></el-option>
        <el-option label="已完成" value="已完成"></el-option>
      </el-select>
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <!-- 工具栏 -->
    <div style="margin: 10px 0">
      <el-button type="danger" @click="delBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="expand" label="明细">
        <template slot-scope="props">
          <div class="detail-table-wrapper">
            <el-table :data="props.row.details" border class="detail-table" show-summary
              :summary-method="getDetailSummary">
              <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
              <el-table-column label="商品图片" width="120" align="center">
                <template slot-scope="scope">
                  <div class="product-image">
                    <el-image v-if="scope.row.img" style="width: 50px; height: 50px" :src="scope.row.img"
                      :preview-src-list="[scope.row.img]"></el-image>
                    <span v-else>无图片</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="goodsName" label="商品名称"></el-table-column>
              <el-table-column prop="cateName" label="商品类型" width="120"></el-table-column>
              <el-table-column prop="price" label="单价" width="100"
                :formatter="(row) => row.price.toFixed(2)"></el-table-column>
              <el-table-column prop="num" label="数量" width="100"></el-table-column>
              <el-table-column label="小计" width="120">
                <template slot-scope="scope">
                  {{ (scope.row.price * scope.row.num).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号" width="55"></el-table-column>
      <el-table-column prop="no" label="订单号"></el-table-column>
      <el-table-column prop="userName" label="用户"></el-table-column>
      <el-table-column prop="addressName" label="地址"></el-table-column>
      <el-table-column prop="total" label="总金额"></el-table-column>
      <el-table-column label="订单状态">
        <template slot-scope="{row}">
          <el-tag size="medium" type="warning" v-if="row.status == '待付款'">待付款</el-tag>
          <el-tag size="medium" type="danger" v-if="row.status == '待发货'">待发货</el-tag>
          <el-tag size="medium" type="primary" v-if="row.status == '待收货'">待收货</el-tag>
          <el-tag size="medium" type="success" v-if="row.status == '已完成'">已完成</el-tag>
          <el-tag size="medium" type="info" v-if="row.status == '已关闭'">已关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="下单时间" width="160"></el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="danger" @click="del(scope.row.id)">删除 <i class="el-icon-remove-outline"></i></el-button>
          <el-button type="warning" v-if="scope.row.status == '待发货'" @click="confirmShipment(scope.row.id)">发货</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="padding: 10px 0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum" :page-sizes="[2, 5, 10, 20]" :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加/修改对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false"
      @close="handleDialogClose">
        <el-form label-width="140px" size="small" style="width: 85%;" :model="form" :rules="rules" ref="dialogForm">
        <el-form-item prop="no" label="订单号">
          <el-input v-model="form.no" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="userId" label="用户">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="addressId" label="地址">
          <el-input v-model="form.addressName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="total" label="总金额">
          <el-input v-model="form.total" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Orders",
  data() {
    return {
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 查询条件
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
      },
      // 表单数据
      form: {},
      // 对话框标题
      dialogTitle: "",
      // 对话框是否显示
      dialogFormVisible: false,
      // 批量选择
      multipleSelection: [],
      // 用户信息
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      // 校验规则
      rules: {
        no: [
          { required: true, message: '请输入订单号', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请输入用户', trigger: 'blur' }
        ],
        addressId: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        total: [
          { required: true, message: '请输入总金额', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请输入订单状态', trigger: 'blur' }
        ],
      },
      // 用户数据
      userData: [],
      // 地址数据
      addressData: [],
    }
  },
  created() {
    this.load()
  },
  methods: {
    // 加载数据
    load() {
      // 加载订单
      this.request.get("/orders/page", {
        params: this.queryInfo
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    // 添加
    handleAdd() {
      this.dialogTitle = "添加订单"
      this.dialogFormVisible = true
    },
    // 修改
    async handleEdit(id) {
      const res = await this.request.get("/orders/" + id)
      this.form = res.data
      this.dialogTitle = "修改订单"
      this.dialogFormVisible = true
    },
    // 保存
    save() {
      this.$refs.dialogForm.validate(async valid => {
        if (!valid) {
          return
        }
        const res = await this.request.post("/orders", this.form)
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        }
        this.$message.success("保存成功")
        this.dialogFormVisible = false
        this.load()
      })
    },
    // 删除
    del(id) {
      this.$confirm('是否确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 删除
          const res = await this.request.delete("/orders/" + id)
          if (res.code !== 200) {
            return this.$message.error("删除失败：" + res.msg)
          }
          this.$message.success("删除成功")
          // 判断当前页最后一条数据
          if (this.tableData.length === 1 && this.queryInfo.pageNum > 1) {
            this.queryInfo.pageNum--
          }
          // 重新加载数据
          this.load()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 批量删除
    delBatch() {
      if (this.multipleSelection.length == 0) {
        this.$message.error("请选择需要删除的数据")
        return
      }
      this.$confirm('是否确定删除该数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 删除
          let ids = this.multipleSelection.map(item => item.id)
          const res = await this.request.delete("/orders/del/batch", { data: ids })
          if (res.code !== 200) {
            return this.$message.error("批量删除失败：" + res.msg)
          }
          this.$message.success("删除成功")
          // 判断当前页最后一条数据
          if (this.tableData.length === ids.length && this.queryInfo.pageNum > 1) {
            this.queryInfo.pageNum--
          }
          // 重新加载数据
          this.load()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 重置
    reset() {
      this.queryInfo = {
        pageNum: 1,
        pageSize: 5
      }
      this.load()
    },
    // 监听页大小改变
    handleSizeChange(pageSize) {
      this.queryInfo.pageSize = pageSize
      this.load()
    },
    // 监听页码改变
    handleCurrentChange(pageNum) {
      this.queryInfo.pageNum = pageNum
      this.load()
    },
    // 文件上传成功的回调
    handleFileUploadSuccess(res) {
      this.form.file = res
    },
    // 图片上传成功的回调
    handleImgUploadSuccess(res) {
      this.form.img = res
    },
    // 下载
    download(url) {
      window.open(url)
    },
    // 导出
    exp() {
      window.open("http://localhost:7777/orders/export")
    },
    // 导入
    handleExcelImportSuccess() {
      this.$message.success("导入成功")
      this.load()
    },
    // 对话框关闭
    handleDialogClose() {
      this.dialogFormVisible = false
      this.form = {}
      this.$refs.dialogForm.resetFields() // 重置表单
      if (this.$refs.img) {
        this.$refs.img.clearFiles();
      }
      if (this.$refs.file) {
        this.$refs.file.clearFiles();
      }
    },

    // 确认发货
    async confirmShipment(id) {
      this.$confirm('是否确认发货？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await this.request.put(`/orders/${id}/status`, { status: '待收货' })
          if (res.code !== 200) {
            return this.$message.error(res.msg)
          }
          this.$message.success("发货成功，订单状态已更新为待收货")
          this.load()
        })
        .catch(() => {
          this.$message({ type: 'info', message: '已取消' })
        })
    },
    // 订单明细合计方法
    getDetailSummary(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        // 计算数量合计
        if (column.property === 'num') {
          const totalNum = data.reduce((prev, curr) => {
            const value = curr[column.property];
            return prev + (Number(value) || 0);
          }, 0);
          sums[index] = totalNum;
          return;
        }
        // 计算金额合计
        if (column.label === '小计') {
          const totalPrice = data.reduce((prev, curr) => {
            const value = (curr.price * curr.num);
            return prev + (Number(value) || 0);
          }, 0);
          sums[index] = totalPrice.toFixed(2);
          return;
        }
        sums[index] = '';
      });
      return sums;
    },
  }
}
</script>

<style scoped style="less">
.search {
  margin: 10px 0;

  .el-input {
    width: 150px;
    margin-right: 10px;
  }

  .el-select {
    width: 140px;
    margin-right: 10px;
  }
}

.headerBg {
  background: #eee !important;
}

/* 订单明细表格样式 */
.detail-table-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  margin: 10px 0;
}

.detail-table {
  width: 90% !important;
  max-width: 1400px;
}

/* 为商品图片添加适当的样式 */
.product-image {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
}
</style>